﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace OpenSearch.Client
{
    public class SearchClientManager
    {
        private readonly ISearchProviderFactory _factory;

        public ReadOnlyObservableCollection<SearchClient> Clients
        {
            get;
            private set;
        }

        public SearchClientManager(ISearchProviderFactory factory)
        {
            _factory = factory;

            Initialize();
        }

        public SearchClientManager()
        {
            _factory = new FakeSearchProviderFactory();

            Initialize();
        }

        private void Initialize()
        {
            var collection = new ObservableCollection<SearchClient>();
            Clients = new ReadOnlyObservableCollection<SearchClient>(collection);

            foreach (var info in _factory.GetProviders())
            {
                var client = new SearchClient(info);
                client.PropertyChanged += Client_PropertyChanged;

                collection.Add(client);    
            }
        }

        private void Client_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // Push to all if search terms changes
            if (e.PropertyName == "SearchTerms")
                SetTerms(((SearchClient)sender).SearchTerms);
        }

        private void SetTerms(string terms)
        {
            Clients.Run(c => c.SearchTerms = terms);
        }

        public void SetCurrentUri(Uri uri)
        {
            Clients.Run(c => c.UpdateTermsFromCurrent(uri));
        }
    }
}
